package com.e.h.sheep.etalk;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Gchat extends Activity implements OnClickListener{

	private ArrayList<String> arrayListSend = new ArrayList<String>();
	private ArrayList<String> arrayListReceive= new ArrayList<String>();
//    public ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

	private Button account, connect;

	private String id,pass;
	private  final String GTALK_HOST = "talk.google.com";
	private  final int GTALK_PORT = 5222;
	private  final String GTALK_SERVICE = "gmail.com";
	private  EditText editText1;
	//	private  TextView receive;
	private Button btn;
	private  Handler handler;
	private Chat chat = null;
	private String toAddress;
	final String TAG = "chatLog";
	public String receiveText = "";
	public LinearLayout layout,layout_recive;

	PacketFilter filter;
	//	public String msg_body;

	ConnectionConfiguration connectionConfiguration;
	XMPPConnection xmppCon;

	public void onCreate(Bundle bundle){
		super.onCreate(bundle);
		//		main = (LinearLayout) findViewById(R.layout.gchat); 
		setContentView(R.layout.gchat);
		layout = (LinearLayout) findViewById(R.id.layout);
		layout_recive = (LinearLayout) findViewById(R.id.layout);

		//	    ScrollView scrollView = new ScrollView(this);
		//	    // View に ScrollView を設定
		//	    setContentView(scrollView);
		//	    LinearLayout linearLayout = new LinearLayout(this);
		//	    linearLayout.setOrientation(LinearLayout.VERTICAL);
		//	    // ScrollView に LinearLayout を追加
		//	    scrollView.addView(linearLayout);

		editText1 = (EditText)findViewById(R.id.editText1);
		btn = (Button)findViewById(R.id.button1);

		//		TextView receive = (TextView)findViewById(R.id.receive);


	}



	public void  onStart() {
		super.onStart();

		Log.d("log", "connect");

		System.setProperty("java.net.preferIPv6Addresses", "false");

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		id = prefs.getString("id", "");
		pass = prefs.getString("pass", "");

		SmackConfiguration.setPacketReplyTimeout(10000);


		Connection.DEBUG_ENABLED = true;
		connectionConfiguration = new ConnectionConfiguration(GTALK_HOST,GTALK_PORT,GTALK_SERVICE);
		connectionConfiguration.setKeystoreType("bks");
		String path = System.getProperty("javax.net.ssl.trustStore");
		if (path == null)
			path = System.getProperty("java.home") + File.separator + "etc"
					+ File.separator + "security" + File.separator
					+ "cacerts.bks";

		connectionConfiguration.setTruststorePath(path);
		connectionConfiguration.setTruststorePassword("changeit");
		connectionConfiguration.setTruststoreType("BKS");
		connectionConfiguration.setSecurityMode(SecurityMode.enabled);
		connectionConfiguration.setSASLAuthenticationEnabled(true);

		connectionConfiguration.setSendPresence(true);


		xmppCon = new XMPPConnection(connectionConfiguration);


	
		
		
		
		
		try {
			xmppCon.connect();
	
			xmppCon.login(id, pass);
		
			displayBuddyList();
			//										ステップ実行ではうまくいかない
		} catch (XMPPException e) {
			e.printStackTrace();
		}

		
		
		Intent intent = getIntent();
		toAddress = intent.getStringExtra("toAddress");

		setPacketFilters();
		receiveThread();

	}

	@Override
	public void onClick(View v) {
		// ソフトキーボード開けている閉じたいEditTextオブジェクトを呼び出す
		EditText ed = (EditText)findViewById(R.id.editText1);
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
		// ボタンを押したときにソフトキーボードを閉じる
		inputMethodManager.hideSoftInputFromWindow(ed.getWindowToken(),0);
		//				handler = new Handler();
		//		
		//				new Thread(new Runnable() {
		//					@Override
		//					public void run() {
		//						// TODO 自動生成されたメソッド・スタブ
		//						handler.post(new Runnable() {
		//		
		//							@Override
		//							public void run() {
		//								// TODO 自動生成されたメソッド・スタブ




		//						}
		//						});
		//					}
		//				}).start();
		//        
		ChatManager chatManager = this.xmppCon.getChatManager();
		chat = chatManager.createChat(toAddress, new MessageListener() {
			public void processMessage(Chat chat, Message message) {
				//			Log.d("chatLog", ": " + message.getBody());
				// receive message

			}


		});

		try {
			//           newChat.sendMessage("test");
			View view = getLayoutInflater().inflate(R.layout.speak, null);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			layoutParams.gravity = Gravity.RIGHT;
			view.setLayoutParams(layoutParams);

			layout.addView(view);
			TextView send = (TextView) view.findViewById(R.id.speak);

			String sendText = editText1.getText().toString();
			chat.sendMessage(sendText);
			arrayListSend.add(sendText);
			send.setText(sendText);
			Log.v(TAG, "Send message:" + arrayListSend.get(arrayListSend.size() -1 ));



		} catch (XMPPException e) {
			Log.v(TAG, "couldn't send:" + e.toString());
		}
		editText1.setText("");




	}


	private void setPacketFilters() {
		if (this.xmppCon != null) {
			PacketFilter presenceFilter = new PacketTypeFilter(Presence.class);
			this.xmppCon.addPacketListener(new PacketListener() {
				public void processPacket(Packet packet) {
					Presence presence = (Presence) packet;
					//					handlePresenceReceived(presence);
				}
			}, presenceFilter);

			PacketFilter messageFilter = new MessageTypeFilter(
					Message.Type.chat);
			this.xmppCon.addPacketListener(new PacketListener() {
				public void processPacket(Packet packet) {
					Message message = (Message) packet;
					if (message.getBody() != null) {
						//						this.activity.handleMessageReceived(message);
						receiveText = message.getBody();

						arrayListReceive.add(receiveText);

						//				    	View view = getLayoutInflater().inflate(R.layout.speak, null);
						//						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
						//						layoutParams.gravity = Gravity.LEFT;
						//						view.setLayoutParams(layoutParams);
						////						layout_recive.addView(view);
						//						TextView receive = (TextView) view.findViewById(R.id.speak);
						//
						//						receive = (TextView)findViewById(R.id.editText2);
						//						receive.setText(receiveText);



						Log.d(TAG, "recv : " + receiveText);

						//						Log.d(TAG, "Got message:" + arrayListReceive.get(arrayListReceive.size() -1 ));
						//						
						//						btn.setFocusable(true);
						//						btn.setFocusableInTouchMode(true);
						//						btn.requestFocus();

					}
				}
			}, messageFilter);
		}
	}


	public void receiveThread(){
		handler = new Handler();

		new Thread(new Runnable(){
			public void run() {
				// TODO 自動生成されたメソッド・スタブ

				final long delayMillis = 1000;
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO 自動生成されたメソッド・スタブ
						Log.d(TAG, "postdelaeyd");

						if(!receiveText.equals("")){
							View view = getLayoutInflater().inflate(R.layout.speak_receive, null);
							LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
							layoutParams.gravity = Gravity.LEFT;
							view.setLayoutParams(layoutParams);
							layout_recive.addView(view);
							TextView receive = (TextView) view.findViewById(R.id.speak_receive);
							receive.setText(receiveText);
							receiveText = "";
						}

						

						handler.postDelayed(this, delayMillis);
					}
				}, delayMillis);
			}
		}).start();

	}
	
	 public void displayBuddyList() {
		    String user;
		    String status_Message; 
		    int state;
		    Roster roster = xmppCon.getRoster();
		    Collection<RosterEntry> entries = roster.getEntries();

		    Log.d("Roster","Buddy list size :"+entries.size());
		    for (RosterEntry r : entries) {

		        user=r.getUser();
//		        status_Message=retrieveStatusMessage(user);
		        Log.d("Roster","name: "+r.getName()+"  user :"+user);

//		        adapter.add(user);
		        
		    }
		}

	

}
